<template>
  <a-modal
    :visible="visible"
    title="查看检查反馈单"
    cancelText="返回"
    @cancel="cancel"
    width="calc(100% - 240px)"
    :style="{top: '0px', 'margin-left': '240px', maxWidth: '100vw', height: 'calc(100% - 132px)'}"
    :footer="null"
  >
    <a-tabs v-model:activeKey="activeKey" style="margin-top: -20px; height: calc(100vh - 83px);" size="large">
      <a-tab-pane key="1" tab="项目检查情况">
        <a-form
          id="infoDIV"
          ref="jcFormRef"
          layout="inline"
          :model="jcFormState"
          :rules="jcFormRules"
        >
          <a-row style="width: 100%; height: 56px;">
            <a-form-item label="项目类型" ref="xmflei" name="xmflei">
              <a-select v-model:value="jcFormState.xmflei" placeholder="请选择项目类型" style="width: 250px;" @change="changeSelect">
                <a-select-option value="">请选择项目类型</a-select-option>
                <a-select-option value="重大水利工程">重大水利工程</a-select-option>
                <a-select-option value="主要支流治理">主要支流治理</a-select-option>
                <a-select-option value="大中型病险水库除险加固">大中型病险水库除险加固</a-select-option>
                <a-select-option value="大中型病险水闸除险加固">大中型病险水闸除险加固</a-select-option>
                <a-select-option value="新建中型水库工程">新建中型水库工程</a-select-option>
                <a-select-option value="新建小型水库工程">新建小型水库工程</a-select-option>
                <a-select-option value="小型病险水库除险加固">小型病险水库除险加固</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="项目名称" ref="xmid" name="xmid">
              <a-select v-model:value="jcFormState.xmid" style="width: 579px;" @change="doChangexmxx">
                <a-select-option
                  :value="xmxx.id"
                  :xmfr="xmxx.xmfr"
                  :cjdw="xmxx.zhongbiaoren"
                  :shimc="xmxx.shimc"
                  :xianmc="xmxx.xianmc"
                  :shi="xmxx.shi"
                  :xian="xmxx.xian"
                  :xmfrid="xmxx.xmfrid"
                  v-bind:key="index"
                  v-for="(xmxx,index) in state.xmxxs"
                >{{xmxx.xmmc}}</a-select-option>
              </a-select>
              <input type="hidden" id="xmmc" name="xmmc">
            </a-form-item>
            <a-form-item label="所在市" ref="shimc" name="shimc">
              <a-input v-model:value="jcFormState.shimc" style="width: 200px"/>
              <input type="hidden" id="shi" name="shi">
            </a-form-item>
            <a-form-item label="所在县" ref="xianmc" name="xianmc">
              <a-input v-model:value="jcFormState.xianmc" style="width: 200px"/>
              <input type="hidden" id="xian" name="xian">
            </a-form-item>
          </a-row>

          <a-row style="width: 100%; height: 56px;">
            <a-form-item label="项目法人" ref="xmfren" name="xmfren">
              <a-input v-model:value="jcFormState.xmfren" style="width: 250px"/>
              <input type="hidden" id="xmfrid" name="xmfrid">
            </a-form-item>
            <a-form-item label="参建单位" ref="cjdwei" name="cjdwei">
              <a-input v-model:value="jcFormState.cjdwei" style="width: 829px"/>
            </a-form-item>
            <a-form-item label="质量监督单位" ref="qsdwei" name="qsdwei">
              <a-input v-model:value="jcFormState.qsdwei" style="width: 190px"/>
            </a-form-item>
          </a-row>

          <a-row style="width: 100%; height: 120px;">
            <a-form-item label="主要问题" ref="fxzywtqk" name="fxzywtqk">
              <a-textarea v-model:value="jcFormState.fxzywtqk" style="width: 1478px; height: 100px;" @focus="getFocusArea('fxzywtqk')" @keyup="getKeyupFxwt($event)"/>
            </a-form-item>
          </a-row>

          <a-row style="width: 100%; height: 100%;">
            <a-form-item label="问题照片">
              <div>
                <a-upload
                  :action="actionUrl"
                  :multiple="true"
                  v-model:file-list="fileListPhotos"
                  :headers="headers"
                  accept="image/*"
                  @preview="handlePreview"
                  class="xmjcfile"
                  :customRequest="uploadImages"
                >
                  <a-button type="primary">
                    <upload-outlined></upload-outlined>
                    上传问题照片
                  </a-button>
                </a-upload>
                <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                  <img alt="example" style="width: 100%" :src="previewImage" />
                </a-modal>
                <a-input type="hidden" v-model:value="jcFormState.photo" id="photo" name="photot"/>
              </div>
            </a-form-item>
          </a-row>

          <a-row style="width: 100%; height: 120px;">
            <a-form-item label="意见建议" ref="gzyjjyqk" name="gzyjjyqk">
              <a-textarea v-model:value="jcFormState.gzyjjyqk" style="width: 1478px; height: 100px;" @focus="getFocusArea('gzyjjyqk')" @keyup="getKeyupYjjy($event)"/>
            </a-form-item>
          </a-row>

          <a-row style="width: 100%; height: 56px;">
            <a-form-item label="完成时限" ref="wcsxian" name="wcsxian">
              <a-date-picker v-model:value="jcFormState.wcsxian" valueFormat="YYYY-MM-DD" id="wcsxian" name="wcsxian"/>
            </a-form-item>
            <a-form-item label="检查单位" ref="jcdwei" name="jcdwei">
              <a-input v-model:value="jcFormState.jcdwei" style="width: 419px"/>
            </a-form-item>
            <a-form-item label="检查人" ref="inspectors" name="inspectors">
              <a-input v-model:value="jcFormState.inspectors" style="width: 419px"/>
            </a-form-item>
            <a-form-item label="检查时间" ref="jcsjian" name="jcsjian">
              <a-date-picker v-model:value="jcFormState.jcsjian" valueFormat="YYYY-MM-DD" id="jcsjian" name="jcsjian"/>
            </a-form-item>
          </a-row>

          <a-row style="width: 100%; height: 100%;">
            <a-form-item label="检查文件">
              <div>
                <a-upload
                  :action="actionUrl"
                  :multiple="true"
                  v-model:file-list="fileListFujian"
                  :headers="headers"
                  accept=".jpg, .jpeg, .png, .pdf, .doc, .docx, .wps"
                  class="xmjcfile"
                  :customRequest="uploadFile"
                >
                  <a-button type="primary">
                    <upload-outlined></upload-outlined>
                    上传文件
                  </a-button>
                </a-upload>
                <a-input type="hidden" v-model:value="jcFormState.fujian" id="fujian" name="fujian"/>
              </div>
            </a-form-item>
          </a-row>
        </a-form>

        <div style="text-align: center;">
            <span style="margin-right: 5px;" v-if="jcFormState.dataztai == '1' || jcFormState.creatorid == thirdFormState.userid">
              <a-button style="background-color: forestgreen; color: white; margin-right: 5px;" @click="subSave">保存</a-button>
              <a-button type="primary" @click="submit">提交</a-button>
            </span>
          <span style="margin-right: 5px;" v-if="jcFormState.dataztai == '1' && thirdFormState.tage == '5' && jcFormState.dataztai == '0' && jcFormState.jcztai != '0' ">
              <a-button type="primary" @click="submit">提交</a-button>
            </span>
          <span style="margin-right: 5px;" v-if="jcFormState.dataztai == '0' && jcFormState.jcztai == '0'">
              <a-button style="background-color: forestgreen; color: white;" @click="submit">撤销</a-button>
            </span>
          <a-button @click="cancel">返回</a-button>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="项目整改情况">
        <a-form
          class="zginfoDIV"
          ref="zgFormRef"
          layout="inline"
          :model="jcFormState"
          :rules="zgFormRules"
        >
          <a-row style="width: 100%; height: 120px;">
            <a-form-item label="整改情况说明" ref="zgqkuang" name="zgqkuang">
              <a-textarea v-model:value="zgFormState.zgqkuang" style="width: 1478px; height: 100px;"/>
            </a-form-item>
          </a-row>

          <a-row style="width: 100%; height: 100%;">
            <a-form-item label="整改相关文件">
              <div>
                <a-upload
                  :action="actionUrl"
                  :multiple="true"
                  v-model:file-list="fileListFujianZG"
                  :headers="headers"
                  accept=".jpg, .jpeg, .png, .pdf, .doc, .docx, .wps, .xls, .xlsx"
                  class="xmjcfile"
                  :customRequest="uploadZgFile"
                >
                  <a-button type="primary">
                    <upload-outlined></upload-outlined>
                    上传文件
                  </a-button>
                </a-upload>
                <a-input type="hidden" v-model:value="zgFormState.fujian" id="fujian" name="fujian"/>
              </div>
            </a-form-item>
          </a-row>

          <a-row>
            <a-form-item label="整改完成" ref="zgstate" name="zgstate">
              <a-select v-model:value="zgFormState.zgstate" placeholder="是否整改完成" style="width: 250px;">
                <a-select-option value="on">是</a-select-option>
                <a-select-option value="off">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-row>
        </a-form>

        <div style="text-align: center;">
            <span v-if="thirdFormState.tage == '1' || thirdFormState.tage == '2' || thirdFormState.tage == '3' || thirdFormState.tage == '4'">
              <span v-if="jcFormState.jcztai == '1'">
                <a-button style="background-color: #ffb800; color: white; margin-right: 5px;" @click="doChangeState(zgFormState.id)">审核通过</a-button>
                <a-button @click="doReturnState(zgFormState.id)">返回完善</a-button>
              </span>
            </span>
            <span v-if="jcFormState.dataztai == '0' && thirdFormState.tage == '5' && jcFormState.jcztai != '0'">
              <a-button type="primary" @click="submitzg">提交</a-button>
            </span>
          <a-button @click="cancel">返回</a-button>
        </div>
      </a-tab-pane>
    </a-tabs>
  </a-modal>
</template>

<script>
import {xmlist, edit, upload, zgdata, zgedit, wtzgUpdateState} from '@/api/module/xmjcha';
import {profile} from '@/api/module/user';
import {getdept} from "@/api/module/dept";
import {createVNode, defineComponent, reactive, ref, toRaw, watch} from "vue";
import $ from "jquery";
import {message, modal} from "ant-design-vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";

var state;

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default defineComponent({
  props: {
    visible: {
      type: Boolean,
    },
    record: {
      type: Object,
    }
  },
  emit: ["close"],

  setup(props, context) {
    const jcFormRef = ref();
    const zgFormRef = ref();

    const state = reactive({
      xmxxs: [],
    })

    const jcFormState = reactive({});
    const zgFormState = reactive({
      zgstate: true
    });
    const thirdFormState = reactive({});

    const jcFormRules = {
      xmflei: [
        { required: true, message: '请选择项目类型', trigger: 'change'},
      ],
      xmid: [
        { required: true, message: '请选择项目', trigger: 'change'},
      ],
      xmfren: [
        { required: true, message: '请完善信息填报内的法人数据', trigger: 'blur'},
      ],
      wcsxian: [
        { required: true, message: '请选择完成时限',},
      ],
      jcdwei: [
        { required: true, message: '请选输入检查单位', trigger: 'blur'},
      ],
      jcsjian: [
        { required: true, message: '请选择检查时间',},
      ],
    };
    const zgFormRules = {};

    ///提交
    const submit = (e) => {
      jcFormState.dataztai = '0';
      jcFormRef.value.validate().then(() => {
        edit(toRaw(jcFormState)).then((response)=>{
          if(response.success){
            message.success({ content: '提交成功', duration: 1 }).then(()=>{
              cancel();
            });
          }else{
            message.error({ content: '提交失败', duration: 1 }).then(()=>{
              cancel();
            });
          }
        })
      }).catch(error => {
        console.log('error', error);
      });
    };
    ///保存
    const subSave = (e) => {
      jcFormState.dataztai = '1';
      jcFormRef.value.validate().then(() => {
        edit(toRaw(jcFormState)).then((response)=>{
          if(response.success){
            message.success({ content: '保存成功', duration: 1 }).then(()=>{
              cancel();
            });
          }else{
            message.error({ content: '保存失败', duration: 1 }).then(()=>{
              cancel();
            });
          }
        })
      }).catch(error => {
        console.log('error', error);
      });
    }

    ///整改提交
    const submitzg = (e) => {
      zgFormRef.value.validate().then(() => {
        zgedit(toRaw(zgFormState)).then((response)=>{
          if(response.success){
            message.success({ content: '提交成功', duration: 1 }).then(()=>{
              cancel();
            });
          }else{
            message.error({ content: '提交失败', duration: 1 }).then(()=>{
              cancel();
            });
          }
        })
      }).catch(error => {
        console.log('error', error);
      });
    }

    var options;
    const changeSelect = function (value) {
      jcFormState.xmid = '';
      jcFormState.xmmc = '';
      jcFormState.shimc = '';
      jcFormState.shi = '';
      jcFormState.xianmc = '';
      jcFormState.xian = '';
      jcFormState.xmfren = '';
      jcFormState.xmfrid = '';
      jcFormState.cjdwei = '';

      xmlist({'report_index': value}).then((response) => {
        state.xmxxs = response.data;
        options = ref(state.xmxxs)
      })
    };

    const doChangexmxx = function (value){
      const selectedOption = options.value.find(xmxx => xmxx.id === value);
      jcFormState.xmmc = selectedOption.xmmc;
      jcFormState.shimc = selectedOption.shimc;
      jcFormState.shi = selectedOption.shi;
      jcFormState.xianmc = selectedOption.xianmc;
      jcFormState.xian = selectedOption.xian;
      jcFormState.xmfren = selectedOption.xmfr;
      jcFormState.xmfrid = selectedOption.xmfrid;
      jcFormState.cjdwei = selectedOption.dfjb;
    }

    /// 修改内容
    const getFocusArea = (id) => {
      var _val = $("#"+ id).val();
      if (0 >= _val.length) {
        $("#"+ id).val("1. ");
      }
    };

    ///回车事件
    var wtcount = 1;
    const getKeyupFxwt = (e) => {
      if (e.keyCode == 13) {
        var content = $("#fxzywtqk").val();
        wtcount = wtcount +1;
        $("#fxzywtqk").val(content + wtcount +". ");
      }
    }
    var jycount = 1;
    const getKeyupYjjy = (e) => {
      if (e.keyCode == 13) {
        var content = $("#gzyjjyqk").val();
        jycount = jycount +1;
        $("#gzyjjyqk").val(content + jycount +". ");
      }
    }

    const loadwindows = () => {
      profile({}).then((response) => {
        jcFormState.inspectors = response.data.nickname;
        thirdFormState.tage = response.data.tage;
        thirdFormState.userid = response.data.id;
        getdept({'id': response.data.deptId}).then((response) => {
          jcFormState.jcdwei = response.data.name
        })
      });
    }

    loadwindows();

    const fileListPhotos = ref([]);
    const fileListFujian = ref([]);
    const fileListFujianZG = ref([]);

    watch(props,(props) => {
      xmlist({'report_index': props.record.xmflei}).then((response) => {
        state.xmxxs = response.data;
        options = ref(state.xmxxs)
      })

      jcFormState.id = props.record.id;
      jcFormState.xmflei = props.record.xmflei;
      jcFormState.xmid = props.record.xmid;
      jcFormState.xmmc = props.record.xmmc;
      jcFormState.shimc = props.record.shimc;
      jcFormState.shi = props.record.shi;
      jcFormState.xianmc = props.record.xianmc;
      jcFormState.xian = props.record.xian;
      jcFormState.xmfren = props.record.xmfren;
      jcFormState.xmfrid = props.record.xmfrid;
      jcFormState.cjdwei = props.record.cjdwei;
      jcFormState.qsdwei = props.record.qsdwei;
      jcFormState.fxzywtqk = props.record.fxzywtqk;
      jcFormState.photo = props.record.photo;
      jcFormState.gzyjjyqk = props.record.gzyjjyqk;
      jcFormState.wcsxian = props.record.wcsxian;
      jcFormState.jcdwei = props.record.jcdwei;
      jcFormState.inspectors = props.record.inspectors;
      jcFormState.jcsjian = props.record.jcsjian;
      jcFormState.fujian = props.record.fujian;
      jcFormState.dataztai = props.record.dataztai;
      jcFormState.creatorid = props.record.creatorid;
      jcFormState.jcztai = props.record.jcztai;

      fileListPhotos.value = [];
      if (null != props.record.photo && '' != props.record.photo) {
        let list = props.record.photo.split(",");
        for (let i = 0; i < list.length; i++) {
          let ee = {};
          ee.uid = i+1;
          ee.name = list[i];
          ee.status = "done";
          ee.url = "/file/xmjcha/"+ list[i];
          fileListPhotos.value.push(ee);
        }
      }

      fileListFujian.value = [];
      if (null != props.record.fujian && '' != props.record.fujian) {
        let list = props.record.fujian.split("#");
        for (let i = 0; i < list.length; i++) {
          let ee = {};
          ee.uid = i + 1;
          ee.name = list[i];
          ee.status = "done";
          ee.url = "/file/xmjcha/"+ list[i];
          fileListFujian.value.push(ee);
        }
      }

      zgdata({"id": jcFormState.id}).then((response) => {
        if (null != response.data){
          zgFormState.id = response.data.id;
          zgFormState.wtzgid = response.data.wtzgid;
          zgFormState.zgqkuang = response.data.zgqkuang;
          zgFormState.fujian = response.data.fujian;
          zgFormState.bzhu = response.data.bzhu;
          zgFormState.zgstate = response.data.zgstate;

          fileListFujianZG.value = [];
          if (null != response.data.fujian && '' != response.data.fujian) {
            let list = response.data.fujian.split(",");
            for (let i = 0; i < list.length; i++) {
              let ee = {};
              ee.uid = i+1;
              ee.name = list[i];
              ee.status = "done";
              ee.url = "/file/xmjcha/"+ list[i];
              fileListFujianZG.value.push(ee);
            }
          }
        } else {
          zgFormState.id = '';
          zgFormState.wtzgid = jcFormState.id;
          zgFormState.zgqkuang = '';
          zgFormState.fujian = '';
          zgFormState.bzhu = '';
          zgFormState.zgstate = '';
        }
      });
    })

    const tokenKey = localStorage.getItem("token_key");
    const token = localStorage.getItem("token");

    const headers = {
      "Authorization": token,
      "Authorization-key": tokenKey
    };

    const previewVisible = ref(false);
    const previewImage = ref('');

    const handlePreview = async file => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      previewImage.value = file.url || file.preview;
      previewVisible.value = true;
    };

    const handleCancel = () => {
      previewVisible.value = false;
    };

    const actionUrl = () => {
      return "http://localhost:9292/api/project/xmjc/upload";
    }

    const uploadImages = async (e) => {
      const form = new FormData();
      form.append('file', e.file);
      const res = await upload(form);
      if (res){
        e.onSuccess(res.data, e);
        var phototemp = $("#photo").val();
        var photoValue = "";
        if ("" === phototemp || null === phototemp){
          photoValue = res.data.fileName;
        } else {
          photoValue = phototemp +","+ res.data.fileName;
        }
        jcFormState.photo = photoValue;
      }
    }

    const uploadFile = async (e) => {
      const form = new FormData();
      form.append('file', e.file);
      const res = await upload(form);
      if (res){
        e.onSuccess(res.data, e);
        var fujiantemp = $("#fujian").val();
        var fujianValue = "";
        if ("" === fujiantemp || null === fujiantemp){
          fujianValue = res.data.fileName;
        } else {
          fujianValue = fujiantemp +"#"+ res.data.fileName;
        }
        jcFormState.fujian = fujianValue;
      }
    }

    const uploadZgFile = async (e) => {
      const form = new FormData();
      form.append('file', e.file);
      const res = await upload(form);
      if (res){
        e.onSuccess(res.data, e);
        var fujiantemp = $("#fujian").val();
        var fujianValue = "";
        if ("" === fujiantemp || null === fujiantemp){
          fujianValue = res.data.fileName;
        } else {
          fujianValue = fujiantemp +","+ res.data.fileName;
        }
        zgFormState.fujian = fujianValue;
      }
    }

    const doChangeState = (id) => {
      console.log(id)
      modal.confirm({
        title: '您是否要审核通过吗？继续请点击确认！',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        cancelText: '取消',
        onOk() {
          message.loading({ content: "提交中..."});
          wtzgUpdateState({"id": id, "xmid": "0"}).then((response) => {
            if(response.success){
              message.success({content: "审核成功", duration: 1}).then(()=>{
                cancel();
              })
            }else{
              message.error({content: "审核失败", duration: 1})
            }
          })
        }
      })
    }
    const doReturnState = (id) => {
      console.log(id)
      modal.confirm({
        title: '您是否要返回审核吗？继续请点击确认！',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        cancelText: '取消',
        onOk() {
          message.loading({ content: "提交中..."});
          wtzgUpdateState({"id": id, "xmid": "2"}).then((response) => {
            if(response.success){
              message.success({content: "返回审核成功", duration: 1}).then(()=>{
                cancel();
              })
            }else{
              message.error({content: "返回审核失败", duration: 1})
            }
          })
        }
      })
    }

    const cancel = (e) => {
      jcFormRef.value.resetFields();
      //zgFormRef.value.resetFields();
      context.emit("close", false);
      $("#reloadbtn").click();
    };

    return {
      state,
      submitzg,
      submit,
      subSave,
      cancel,
      jcFormRef,
      zgFormRef,
      jcFormState,
      zgFormState,
      thirdFormState,
      jcFormRules,
      zgFormRules,

      changeSelect,
      getFocusArea,
      getKeyupFxwt,
      getKeyupYjjy,
      doChangexmxx,

      headers,
      fileListPhotos,
      fileListFujian,
      fileListFujianZG,
      previewVisible,
      previewImage,
      handlePreview,
      handleCancel,
      actionUrl,
      uploadImages,
      uploadFile,
      uploadZgFile,

      doChangeState,
      doReturnState,

      activeKey: ref('1'),
    }
  },
});
</script>

<style scoped>
#infoDIV .ant-form-item-label{
  width: 100px !important;
}
.zginfoDIV :deep(.ant-form-item-label){
  width: 100px !important;
}

/* tile uploaded pictures */
.xmjcfile :deep(.ant-upload-list) {
  width: 1478px;
  margin-bottom: 20px;
}
</style>
